package com.example.javabase.DesignPattern.Strategy;

import org.apache.commons.jexl3.*;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * @author: wyb
 * @date: 2021/11/3 16:09
 * @describe: 通过script脚本进行计算，数学公式等
 * @vision 1.0
 */
@Component
public class ScriptApiCalculateHandler extends AbstractInstrCalculateHandler{
    
    @Override
    protected Object handler(String formula, Map<String, Object> instrsValue) {
        JexlEngine engine = new JexlBuilder().create();
        JexlScript script = engine.createScript(formula);
        JexlContext context = new MapContext();
        if (Objects.nonNull(instrsValue)) {
            instrsValue.forEach(context::set);
        }
        return script.execute(context);
    }
}
